﻿// Copyright (c)  MOKEYISH. All rights reserved.
// Licensed under the MIT License, See License.txt in the project root for license information.

using Antlr4.Runtime;
using NSQL.Expressions;
using NSQL.Parser.Grammars;
using NSQL.Statements;

namespace NSQL.Parser
{
    public static class SqlParser
    {

        public static IStatement ParseStatement(string statement)
        {
            if (string.IsNullOrWhiteSpace(statement)) return null;
            var parser = new NSQL.Parser.Grammars.NSqlParser(
                new CommonTokenStream(new NSqlLexer(new AntlrInputStream(statement))));
            var visitor = new NSqlGrammarVisitor();
            return (IStatement) visitor.VisitUnit_statement(parser.unit_statement());
        }
        
        public static IExpression ParseExpression(string expression)
        {
            if (string.IsNullOrWhiteSpace(expression)) return null;
            var parser = new NSQL.Parser.Grammars.NSqlParser(
                new CommonTokenStream(new NSqlLexer(new AntlrInputStream(expression))));
            var visitor = new NSqlGrammarVisitor();
            return (IExpression) visitor.VisitExpression(parser.expression());
        }

        public static ILogicalExpression ParseLogicalExpression(string expression)
        {
            if (string.IsNullOrWhiteSpace(expression)) return null;
            var parser = new NSQL.Parser.Grammars.NSqlParser(
                new CommonTokenStream(new NSqlLexer(new AntlrInputStream(expression))));
            var visitor = new NSqlGrammarVisitor();
            return (ILogicalExpression) visitor.VisitLogical_expression(parser.logical_expression());
        }

        public static bool TestSyntax(string sql)
        {
            var parser = new NSQL.Parser.Grammars.NSqlParser(
                new CommonTokenStream(new NSqlLexer(new AntlrInputStream(sql))));
            return parser.parse() != null && parser.NumberOfSyntaxErrors == 0;
        }
    }
}